package struts.com;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import struts.bean.XmlBean;


public class StrutsConfig {

	public StrutsConfig(){
		
	}
	
	public static Map<String, XmlBean> strutsConfigXml(String url) throws Exception {
		
		Map<String, XmlBean> xmlBeans = new HashMap<String, XmlBean>();
		
		SAXBuilder builder = new SAXBuilder();
		
		Document document = builder.build(new File(url));
		Element root = document.getRootElement();
		
		Element actionMapping = root.getChild("action-mapping");
		List<Element> actionList = actionMapping.getChildren();
		
		for(Element action:actionList) {
			XmlBean xmlBean = new XmlBean();
			
			String actionname = action.getAttributeValue("name");
			String beanclass = "";
			Element formbeans = root.getChild("formbeans");
			List<Element> formbeanList = formbeans.getChildren();
			for(Element bean:formbeanList) {
				String beanname = bean.getAttributeValue("name");
				if (beanname.equals(actionname)) {
					beanclass = bean.getAttributeValue("class");
					break;
				}
			}
			
			String path = action.getAttributeValue("path");
			String type = action.getAttributeValue("type");
			
			Map<String, String> forwordsMap = new HashMap<String, String>();
			List<Element> forwords = action.getChildren();
			for(Element forword:forwords) {
				String forwordname = forword.getAttributeValue("name");
				String forwordvalue = forword.getAttributeValue("value");
				
				forwordsMap.put(forwordname, forwordvalue);
			}
			
			// xmlbean的设定
			xmlBean.setBeanName(actionname);
			xmlBean.setBeanClass(beanclass);
			xmlBean.setActionPath(path);
			xmlBean.setActionClass(type);
			xmlBean.setForwords(forwordsMap);
			xmlBeans.put(path, xmlBean);
		}
		return xmlBeans;
	}
}
